import { login, getUserInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, constantRoutes } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
    routes: constantRoutes // 静态路由的数组
  }
}

const state = getDefaultState()

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  RM_Token(state) {
    // 删除Vuex的token
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes] // 静态路由 + 动态路由
  }
}

const actions = {
  async login(context, data) {
    // todo: 调用登录接口
    const token = await login(data)
    // 返回一个token
    context.commit('SET_TOKEN', token)
  },
  // user logout
  logout(context) {
    resetRouter()
    context.commit('setUserInfo', {})
    context.commit('RM_Token')
  },
  async getUserInfo(context) {
    const result = await getUserInfo()
    context.commit('setUserInfo', result)
    return result // 返回数据
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

